import React, { useState, useEffect } from 'react';
import {
  Form,
  Button,
  Space,
  Row,
  Col,
  Radio,
  Input,
  InputNumber,
  TreeSelect,
  message,
} from 'antd';
import { useModel } from 'umi';
import { FileSearchOutlined } from '@ant-design/icons'
import { addResource, updateResource } from '@/services/menu';

type MenuItemProps = {
  menuInfo: MENU_API.Menu | undefined;
  menuId: string | undefined;
  data: MENU_API.Menu[];
  onClose: () => void;
  toFetchList: () => void;
};

const MenuItem: React.FC<MenuItemProps> = (props) => {
  const { initialState } = useModel('@@initialState');
  const [kind, setKind] = useState<number>();
  const [menuList, setMenuList] = useState<any[]>();
  const [form] = Form.useForm();
  const { menuInfo, menuId, data, onClose, toFetchList } = props;

  useEffect(() => {
    const list = [{ title: '主类目', value: '0', children: data }];
    setMenuList(list);
    if (!menuInfo) {
      setKind(1);
      form.setFieldsValue({ kind: 1, hidden: 0, status: 1, parent_id: menuId });
    } else {
      setKind(menuInfo.kind);
    }
  }, []);

  const onChangeKind = (e: any) => {
    setKind(e.target.value);
  };

  const toSearchIcon = () => {
    window.open(initialState?.sysSettings?.iconfontProjectUrl, '_blank');
  }

  const onFinish = async (values: any) => {
    const rsp = menuInfo
      ? await updateResource({ ...values, id: menuInfo.id })
      : await addResource(values);
    if (rsp.code === 0) {
      message.success(`${menuInfo ? '菜单修改成功' : '新增菜单成功'}`);
      onClose();
      toFetchList();
    }
  };

  return (
    <>
      <Form
        form={form}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        initialValues={menuInfo && { ...menuInfo }}
      >
        <Form.Item
          name="kind"
          label="菜单类型"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          rules={[{ required: true, message: '请选择菜单类型' }]}
        >
          <Radio.Group disabled={menuInfo ? true : false} onChange={onChangeKind}>
            <Radio value={1}>菜单</Radio>
            <Radio value={2}>操作</Radio>
            <Radio value={3}>外部菜单</Radio>
            <Radio value={4}>目录</Radio>
            <Radio value={5}>按钮</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          name="parent_id"
          label="上级菜单"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          rules={[{ required: true, message: '请选择上级菜单' }]}
        >
          <TreeSelect
            showSearch
            allowClear
            treeLine
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择上级菜单"
            treeDefaultExpandAll
            treeNodeFilterProp="title"
            treeData={menuList}
          />
        </Form.Item>
        <Row gutter={10}>
          <Col span={12}>
            <Form.Item
              name="name"
              label="菜单名称"
              rules={[
                { required: true, message: '请输入菜单名称' },
                { pattern: /^[A-Za-z0-9]+$/, message: '请输入字母或者数字类型' },
              ]}
            >
              <Input placeholder="请输入菜单名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              labelCol={{ span: 10 }}
              wrapperCol={{ span: 14 }}
              name="name_cn"
              label="菜单中文名称"
              rules={[{ required: true, message: '请输入菜单中文名称' }]}
            >
              <Input placeholder="请输入菜单中文名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="sort"
              label="排序"
              tooltip="数值越大显示越靠前"
              rules={[{ required: true, message: '请输入排序' }]}
            >
              <InputNumber style={{ width: '100%' }} placeholder="请输入排序" />
            </Form.Item>
          </Col>
          {[1, 3, 4].includes(kind as number) && (
            <Col span={12}>
              <Form.Item
                name="icon"
                label="图标"
                tooltip="点击右侧搜索图标去iconfont搜索所需图标"
                rules={[{ required: false, message: '请输入图标' }]}
              >
                <Input placeholder="请输入图标" addonAfter={<FileSearchOutlined style={{cursor: 'pointer'}} onClick={toSearchIcon}/>} />
              </Form.Item>
            </Col>
          )}
          {[1, 4].includes(kind as number) && (
            <Col span={12}>
              <Form.Item
                name="path"
                label="路由地址"
                rules={[{ required: true, message: '请输入路由地址' }]}
              >
                <Input placeholder="请输入路由地址" />
              </Form.Item>
            </Col>
          )}
          {kind === 1 && (
            <Col span={12}>
              <Form.Item
                name="component"
                label="组件路径"
                rules={[{ required: true, message: '请输入组件路径' }]}
              >
                <Input placeholder="请输入组件路径" />
              </Form.Item>
            </Col>
          )}
          {(kind === 2 || kind === 5) && (
            <Col span={12}>
              <Form.Item
                name="perms"
                label="权限标识"
                rules={[{ required: true, message: '请输入权限标识' }]}
              >
                <Input placeholder="请输入权限标识" />
              </Form.Item>
            </Col>
          )}
          <Col span={12}>
            <Form.Item
              name="status"
              label="状态"
              rules={[{ required: true, message: '请选择状态' }]}
            >
              <Radio.Group buttonStyle="solid">
                <Radio.Button value={0}>停用</Radio.Button>
                <Radio.Button value={1}>启用</Radio.Button>
              </Radio.Group>
            </Form.Item>
          </Col>
          {kind === 1 && (
            <Col span={12}>
              <Form.Item
                name="hidden"
                label="是否显示"
                rules={[{ required: true, message: '请选择是否显示' }]}
              >
                <Radio.Group buttonStyle="solid">
                  <Radio.Button value={0}>是</Radio.Button>
                  <Radio.Button value={1}>否</Radio.Button>
                </Radio.Group>
              </Form.Item>
            </Col>
          )}
        </Row>
        {kind === 3 && (
          <Form.Item
            name="location"
            label="外链地址"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            rules={[{ required: true, message: '请输入外链地址' }]}
          >
            <Input placeholder="请输入外链地址，例如(http://xxxxx.com)" />
          </Form.Item>
        )}
        <Form.Item name="remark" label="备注" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
          <Input.TextArea showCount maxLength={255} placeholder="请输入备注" />
        </Form.Item>
        <Form.Item
          wrapperCol={{ offset: 8, span: 16 }}
          style={{ position: 'absolute', bottom: 0, left: '36%' }}
        >
          <Space>
            <Button type="primary" htmlType="submit">
              {menuInfo ? '保存' : '确定'}
            </Button>
            <Button onClick={onClose}>取消</Button>
          </Space>
        </Form.Item>
      </Form>
    </>
  );
};

export default MenuItem;
